#include "ServerRiotShield.h"

#include <iostream>

void ServerRiotShield::runLogic(){
	pthread_mutex_lock( &shieldLock );
	//std::cout << "server shield runs\n";
	double ax = cRightPressed ? (cLeftPressed ? 0 : SHIELDACCX) : (cLeftPressed ? -SHIELDACCX : 0);
	double ay = cUpPressed ? (cDownPressed ? 0 : SHIELDACCY) : (cDownPressed ? -SHIELDACCY : 0);
	//std::cout << myID << " acceleration " << ax << " " << ay << "\n";
	//std::cout << myID << " pos " << myPos.x << " " << myPos.y << " " << myPos.z << "\n";
	myPos.accelerate(ax,ay,0);
	myPos.accelerateResistance(DECELRX, DECELRY, 0);
	//send data over the network
	int bufferLoc = 0;
	bufferLoc += conv.writeConvertedDouble(myPos.x, (buffer + bufferLoc));
	bufferLoc += conv.writeConvertedDouble(myPos.y, (buffer + bufferLoc));
	bufferLoc += conv.writeConvertedDouble(myPos.z, (buffer + bufferLoc));
	bufferLoc += conv.writeConvertedDouble(myPos.vx, (buffer + bufferLoc));
	bufferLoc += conv.writeConvertedDouble(myPos.vy, (buffer + bufferLoc));
	bufferLoc += conv.writeConvertedDouble(myPos.vz, (buffer + bufferLoc));
	//actually send
	handler->addBroadcastMessage(buffer, bufferLoc, tgt);
	
	pthread_mutex_unlock( &shieldLock );
}

void ServerRiotShield::messageUpdate(char *message, int length){
	pthread_mutex_lock( &shieldLock );
	//std::cout << "server shield" << myID << "get message\n";
	if(length != 4){
		//error, not a good message
		std::cout << "bad message\n";
		exit(0);
	}
	cUpPressed = message[0];
	cDownPressed = message[1];
	cRightPressed = message[2];
	cLeftPressed = message[3];
	
	pthread_mutex_unlock( &shieldLock );
}
